import datarover from "./datarover.mjs";
import { after } from "./delay_render.mjs";
import thin_render from "./thin_render.mjs";

export default function worksheet_template(container, template) {
  let worksheet = document.createElement("worksheet");
  container.appendChild(worksheet);

  let table = document.createElement("table");
  worksheet.appendChild(table);

  let data;
  if (template.data) {
    data = template.data;
  } else if (template.datapath) {
    data = datarover(container, template.datapath);
    if (data === undefined) {
      data = [];
      datarover(container, template, data);
    }
  }

  // 构造行模板
  let row_template = [];
  template.worksheet.forEach((col) => {
    switch (col.type) {
      case "textarea":
        row_template.push({
          td: {
            textarea: col.col,
            bind: col.col,
            event: {
              input: (e) => {
                textarea_height(e.sender);
              },
            },
            afterbind: textarea_height,
          },
        });
        break;
      default:
        row_template.push({
          td: { input: col.col, bind: col.col, type: col.type },
        });
        break;
    }

    function textarea_height(element) {
      element.style.height = "0px";
      element.style.height = `${element.scrollHeight}px`;
    }
  });

  if (Array.isArray(data)) {
    let tbody = document.createElement("tbody");
    table.appendChild(tbody);
    data.forEach((row) => {
      render_row(tbody, row);
    });
  }

  console.log(row_template);

  function render_row(tbody, row, insert) {
    let tr = document.createElement("tr");
    tbody.appendChild(tr);
    tr.thin_data = row;
    thin_render(tr, row_template);
  }
}
